﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Runtime = Microsoft.SqlServer.Dts.Runtime;
using System.IO;
using SSISFromCode.Helpers;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

namespace SSISFromCode
{

    public class XMLColumnReadFailure : Exception
    {
        public XMLColumnReadFailure(): base(MISC.CAINT_DETERMINE_XML_COLS) {}
    }

    internal class XMLGenerator : NonFlatFileGenerator, IPreConfigureColumns, IRequireCleanup
    {

        private string _schemaPath;

        protected override void CreateDataFlowSourceComponent( Runtime.Application app )
        {
            CreateDataFlowSourceComponent( app, OBJECT_CREATION.XML_SOURCE );
        }

        /// <summary>
        /// Pre: ConfigureColumns() has been called
        /// </summary>
        protected override void SetSourceProperties()
        {
            _dataSourceInstance.SetComponentProperty( COMPONENT_PROPERTY_NAMES.XML_FILE, _options.Path );
            _dataSourceInstance.SetComponentProperty( COMPONENT_PROPERTY_NAMES.XML_SCHEMA_FILE, _schemaPath );
        }

        /// <summary>
        /// Configuring columns for an XML data flow requires creating a schema.
        /// This here does the same kind of thing that the "create schema" button in the SSIS designer does.
        /// </summary>
        public void ConfigureColumns()
        {
            _schemaPath = Path.ChangeExtension( Path.GetTempFileName(), "xsd" );
            if ( !new SchemaGenerator().Generate( _options.Path, _schemaPath ) )
            {
                throw new XMLColumnReadFailure();
            }
        }

        /// <summary>
        /// Delete the schema file created in ConfigureColumns()
        /// Note that if you're creating and saving the package (as opposed to executing it), you don't want this to run...
        /// </summary>
        public void Cleanup()
        {
            //Console.WriteLine("Uncomment Cleanup()  !!!!!!!!!!!!!!!!!!!!!!!!!!");
            File.Delete( _schemaPath );
        }

    }

}
